//
//  LeancloudManage.swift
//  MySport
//
//  Created by lanou3g on 16/2/26.
//  Copyright © 2016年 ccsobj. All rights reserved.
//

import UIKit
import AVOSCloud




// 在leancloud注册的相关信息
private let appID = "EHaVrOcUM2RslJD3vl2kLHTG-gzGzoHsz"
private let appKey = "qLq7J5jIoxWFEGy0lxMmslQF"
private let masterKey = "1vWTEjFs32PGuYfcu6eNazg3"

typealias BoolResultClosure = (success:Bool,error:NSError)->Void
typealias ObjectResultClosure = (object:NSObject?)->Void
typealias UserResultClosure = (user:User?,error:NSError?)->Void
typealias FileResultClosure = AVFileResultBlock

typealias AVFileResultClosure = (AVFile?)->Void

typealias StringResultClosure = (NSString?)->Void



class LeancloudManage: NSObject {
    
//    key为文件名，value是leancloud上的objectId
    static var dictOfFileId = [String:String]()
    
    static var urlOfFile = [String:String]()
    
    
    
//  初始化leacloude，与其服务器进行链接
    class func initLeancloude(){
        AVOSCloud.setApplicationId(appID, clientKey:appKey)
    }
    
//  将对象保存到leancloude服务器
    class func saveInstance(instance:AnyObject){
        let className = instance.className
        let dict = instance.propertyList()
        let vcObj = AVObject(className:className,dictionary:dict as! [NSObject : AnyObject])
         vcObj.saveInBackground()
    }
    
//    通过类名在leacloude服务器查询获取数据
//    className所对应类，必须继承NSObject，必须重写setValue forUndefinedKey方法
    class func queryWithClassName(name:String , closure:ObjectResultClosure){
        let query = AVQuery(className:name)
        query.findObjectsInBackgroundWithBlock(){obj,err in
            if let obj = (obj[0] as? AVObject){
                closure(object: obj.commenObject())
            }
        }
    }
    
    class func queryWithClass(clazz:AnyClass, closure:ObjectResultClosure){
       let name = NSStringFromClass(clazz)
        queryWithClassName(name, closure:closure)
    }
}

// 用户相关的工具类方法
extension LeancloudManage{
    //MARk 通过用户名密码注册
    class func signUpWithUser(user:User,complete:BoolResultClosure) {
        let avuser = AVUser.avUser(user)
        avuser.signUpInBackgroundWithBlock {
            complete(success:$0, error:$1)
        }
    }
    
    //    请求短信注册验证码，验证码有效期10分钟
    class func requestMobilePhoneVerify(phonNumber:String,complete:BoolResultClosure){
        AVUser.requestMobilePhoneVerify(phonNumber){complete(success:$0, error:$1)}
    }
    
    //    验证短信验证码是否正确
    class func verifyMobilePhone(verifyNumber:String,complete:BoolResultClosure){
        AVUser.verifyMobilePhone(verifyNumber){complete(success:$0, error:$1)}
    }
    
//    通过用户名密码登陆
    class func login(userName:String,password:String,complete:UserResultClosure){
        AVUser.logInWithUsernameInBackground(userName, password:password) { (avuser, err) -> Void in
            if avuser != nil{
                complete(user:avuser.toUser(), error:nil)
            }else{
                complete(user:nil, error:err)
            }
        }
    }
    
    //    用手机快速登陆,获取验证码
    class func requestSmsCodeWithPhoneNumber(phoneNumber:String,complete:BoolResultClosure){
        AVOSCloud.requestSmsCodeWithPhoneNumber(phoneNumber){complete(success:$0, error:$1)}
    }
    //    手机快速登陆
    class func signUpOrLoginWithPhoneNumber(phoneNumber:String,smsCode:String,copmplete:UserResultClosure) {
        AVUser.signUpOrLoginWithMobilePhoneNumberInBackground(phoneNumber, smsCode:smsCode) { (user, error) -> Void in
            
        }
    }
}

// 文件相关的工具类方法
extension LeancloudManage{
    
//    将图片上传到leancloud服务器，成功后获取图片的url
    class func saveImage(image:UIImage,name:String,compleWithURl:StringResultClosure){
        postImage(image, name:name){
            if let avfile = $0{
                compleWithURl(avfile.url)
            }else{
                compleWithURl(nil)
            }
        }
    }
    
    class func postDict(dict:[String:Any],name:String,complete:StringResultClosure){
//        let doc = 
    }
    
    
    //    通过文件名上传文件，文件必须存在在Bundle当中
    class func postFileWithFilename(filename:String,complete:StringResultClosure){
        let doc = NSBundle.mainBundle().pathForResource(filename, ofType:nil)
        postFileWithPath(doc, name:filename, complete:complete)
    }
    
    class func postFileWithPath(path:String?,name:String,complete:StringResultClosure){
        let file = AVFile(name:name, contentsAtPath:path)
        file.saveWithURLClosure(complete)
    }
    
   private class func postImage(image:UIImage,var name:String,complete:AVFileResultClosure) {
        if let data = UIImageJPEGRepresentation(image, 1){
            if !name.hasSuffix(".jpg"){
                name = name + ".jpg"
            }
            saveFile(name, data:data, complete: complete)
        }else if let data = UIImagePNGRepresentation(image){
            if !name.hasSuffix(".png"){
                name = name + ".png"
            }
            saveFile(name, data:data, complete:complete)
        }
    }
    
   private class func saveFile(name:String,data:NSData,complete:AVFileResultClosure) {
        let file = AVFile(name:name, data:data)
        file.saveWithFileClosue(complete)
    }
    
    private class func saveImageWithName(fileName:String,complete:StringResultClosure) {
        let doc = NSBundle.mainBundle().pathForResource(fileName, ofType:nil)
        let file = AVFile(name:fileName, contentsAtPath:doc)
        file.saveWithURLClosure(complete)
    }
    
//    下载文件
    class func downloanFilewithObjectId(objid:String,complete:(AVFile)->Void){
        AVFile.getFileWithObjectId(objid) { (file, err) -> Void in
            
        }
    }
    
    class func downloanFileWithName(name:String,complete:(AVFile)->Void){
       
        if dictOfFileId[name] == nil { return }
        downloanFilewithObjectId(dictOfFileId[name]!,complete: complete)
    }
}


extension AVUser{
    class func avUser(user:User)->AVUser{
        let avuser = AVUser()
        avuser.username = user.username
        avuser.password = user.password
        avuser.email = user.email
        avuser.mobilePhoneNumber = user.mobilePhoneNumber
        return avuser
    }
    
    func toUser()->User{
        let user = User(withname:self.username, password:self.password, email:self.email, mobilePhoneNumber:self.mobilePhoneNumber)
        return user
    }
    
}


extension AVFile{
    func saveWithFileClosue(complete:AVFileResultClosure){
        self.saveInBackgroundWithBlock(){
            if $0{
                complete(self)
            }else{
                print($1)
            }
        }
    }
    func saveWithURLClosure(complete:StringResultClosure){
        saveWithFileClosue(){
            complete($0?.url)
        }
    }
}


extension AVObject{
    
    func commenObject()->NSObject?{
        let obj = self.className.object()
        let dict = self.dictionaryForObject()
        if let nsobj = obj as? NSObject{
            nsobj.setValuesForKeysWithDictionary(dict as! [String:AnyObject])
            return nsobj
        }
        return nil
    }
    
    func dictionaty()->[String:AnyObject]{
        let keys = self.allKeys()
        var dict = [String:AnyObject]()
        for  key in keys{
            if let k = key as? String{
                dict[k] = self[k]
            }
        }
        return dict
    }
}


